﻿using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {

        [CtxMenuItem("Renderer/Clipboard/Paste/Blend-shapes"
            ,"Pastes blend-shapes from one skinned mesh renderer to another, existing blend-shapes will be skipped",
             ContextFlag.PasteFunction, ContextRequirements.CanPasteBlendshape, 001)]
        public static void RendererPasteBlendshapes()
        {
            var item = SkinnContext.GetContextItem();
            if (item && SkinnEx.IsNullOrNotInAScene(item.transform)) return;
            var context = item.GetComponent<Renderer>();
            if (SkinnEx.IsNullOrNotVailid(context)) return;

            var copyContext = (Renderer)SkinnContext.CopyRef.Asset;
            if (!copyContext) return;
            var copyMesh = copyContext.GetSharedMesh();

            var mesh = context.GetSharedMesh().Clone() as Mesh;

            if (mesh.CopyBlendshapes(copyMesh))
            {
                SkinnContext.UndoRecord(context, "Paste Blend-shapes");
                context.SetSharedMesh(mesh);
            }
            else
            {
                Debug.LogWarning("Paste Blendshapes Failed.");
            }

            SkinnContext.Finished();
        }

        [CtxMenuItem("Renderer/Clipboard/Paste/Mesh As Blend-shape"
           , "Pastes mesh as a blend-shape.",
            ContextFlag.PasteFunction, ContextRequirements.CanPasteVertex, 001)]
        public static void RendererPasteMeshAsShape()
        {
            var item = SkinnContext.GetContextItem();
            if (item && SkinnEx.IsNullOrNotInAScene(item.transform)) return;
            var target = item.GetComponent<Renderer>();
            if (SkinnEx.IsNullOrNotVailid(target)) return;

            var source = (Renderer)SkinnContext.CopyRef.Asset;
            if (SkinnEx.IsNullOrNotVailid(source)) return;

            SkinnContext.UndoRecord(target, "Paste Blend-shapes");

            var newMesh = target.GetSharedMesh().Clone() as Mesh;
            var sourceMesh = source.GetSharedMesh();

            var name = SkinnEx.EnforceString(source.gameObject.name);

            if (name == target.gameObject.name && newMesh.name == sourceMesh.name)
                name = source.transform.root.name;

            if (newMesh.AddBlendshape(sourceMesh, name)) target.SetSharedMesh(newMesh);
            else
            {
                Debug.LogWarning("Skinn: vertex count mismatch paste blend-shapes failed.");
                SkinnEx.Release(newMesh);
            }
            SkinnContext.Finished();
        }

    }
}